using UnityEngine;
using QFramework;
using System;
using System.Collections.Generic;

namespace ProjectSurvivor
{
	// [Serializable]
	// public class EnemyWave
	// {
	// 	public float GenerateDuration = 1;//间隔
	// 	public GameObject EnemyPrefab;
	// 	public int seconds = 10;
	// }
	public partial class EnemyGenerator : ViewController//表示一个挂在场景物体上的控制器（如玩家、刷怪器）。
	{
		[SerializeField]
		public LevelConfig cofig;
		private float mCurrentGenerSeconds = 0;
		private float mCurrentWaveDeconds = 0;
		public static BindableProperty<int> EnemyCount = new BindableProperty<int>(0);
		public Queue<EnemyWave> mEnemyWavesQueue = new Queue<EnemyWave>();

		public int WaveCount;
		public int mTotalCount = 0;
		public bool LastWave => WaveCount == mEnemyWavesQueue.Count;
		public EnemyWave CurrentWave => mCurrentWave;
		public EnemyWave mCurrentWave = null;
		void Start()
		{
			foreach (var group in cofig.EnemyWaveGroups)
			{
				foreach (var wave in group.Waves)
				{
					mEnemyWavesQueue.Enqueue(wave);
					mTotalCount++;
				}
			}
			mCurrentWave = null;
        }
		
        void Update()
		{
			if (mCurrentWave == null)
			{
				if (mEnemyWavesQueue.Count > 0)
				{
					mCurrentWave = mEnemyWavesQueue.Dequeue();
					mCurrentGenerSeconds = 0;
					mCurrentWaveDeconds = 0;
				}
			}
			
			if (mCurrentWave != null)
			{
				mCurrentGenerSeconds += Time.deltaTime;
				mCurrentWaveDeconds += Time.deltaTime;

				if (mCurrentGenerSeconds >= mCurrentWave.GenerateDuration)
				{
					mCurrentGenerSeconds = 0;
					var player = Player.Default;
					if (player)
					{
						var xOry = RandomUtility.Choose(-1,1);
						var pos = Vector2.zero;
						if (xOry == -1)
						{
							pos.x= RandomUtility.Choose(CameraController.Lb.position.x, CameraController.Rt.position.x);
							pos.y= UnityEngine.Random.Range(CameraController.Lb.position.y, CameraController.Rt.position.y);
						}
						else
						{
							pos.x= UnityEngine.Random.Range(CameraController.Lb.position.x, CameraController.Rt.position.x);
							pos.y= RandomUtility.Choose(CameraController.Lb.position.y, CameraController.Rt.position.y);
						}
						// var randomAngle = UnityEngine.Random.Range(0, 360);
						// var randomRadius = randomAngle * Mathf.Deg2Rad;
						// var direction = new Vector3(Mathf.Cos(randomRadius), Mathf.Sin(randomRadius));
						// var genertePos = player.transform.position + direction * 10;
						mCurrentWave.EnemyPrefab.Instantiate().Position(Vector3.zero).Position(pos).Self(self=>
						{
							var enemy = self.GetComponent<IEnemy>();
							enemy.SetSpeesScale(mCurrentWave.SpeedScale);
							enemy.SetHpScale(mCurrentWave.HpScale);
						}).Show();
					}
				}
				if (mCurrentWaveDeconds >= mCurrentWave.Seconds)
				{
					
					mCurrentWave = null;
				}
			}
		}
	}
}
